<template> 
 		<!-- <router-link  to='/project/add/record'>record</router-link> -->
	<a-spin   :indicator="indicator"  tip="正在加载中..."  :spinning='spinning'  :delay="delayTime"> 
 		<a-form :layout="formLayout"  :form="form"  @submit="handleSubmit">
		    <a-form-item
		        label="产品名称"
		        :label-col="formItemLayout.labelCol"
		        :wrapper-col="formItemLayout.wrapperCol"
		      >
		           <a-input  v-decorator="['name',baseform.name]"/>
		    </a-form-item>  
			<a-form-item
		        label="产品类型"
		        :label-col="formItemLayout.labelCol"
		        :wrapper-col="formItemLayout.wrapperCol"
		      >
		           <a-radio-group name="radioGroup" v-decorator="['type',baseform.type]">
				    <a-radio value="1">地产类</a-radio>
				    <a-radio value="2">政信类</a-radio>
				  </a-radio-group>
		      </a-form-item>
		      <a-form-item
		        label="产品规模（万元）"
		        :label-col="formItemLayout.labelCol"
		        :wrapper-col="formItemLayout.wrapperCol"
		      >
		           <a-input-number  placeholder="请输入数字"  style='width:150px'    v-decorator="['size',baseform.size ]"/>
		      </a-form-item>
		      <a-form-item
		        label="融资主体性质"
		        :label-col="formItemLayout.labelCol"
		        :wrapper-col="formItemLayout.wrapperCol"
		      > 
		           <a-select v-decorator="[ 'financingSubjectNature',baseform.financingSubjectNature ]" placeholder='请选择' >	 
					    <a-select-option value="1">政信</a-select-option>
					    <a-select-option value="2">地产</a-select-option>
					    <a-select-option value="3" >国企</a-select-option>
					    <a-select-option value="4">其他行业龙头</a-select-option> 
				    </a-select>
		      </a-form-item>
		    <a-form-item
		        label="起投额（万元）"
		        :label-col="formItemLayout.labelCol"
		        :wrapper-col="formItemLayout.wrapperCol"
		      >
		           <a-input-number  placeholder="请输入数字"  style='width:150px'  v-decorator="['startingAmt',baseform.startingAmt ]"  /> 
		      </a-form-item>
		      <a-form-item
		        label="存续周期（月）"
		        :label-col="formItemLayout.labelCol"
		        :wrapper-col="formItemLayout.wrapperCol"
		      >
		           <a-row :gutter="8">
			        <a-col :span="12">
			          <a-input-number   style='width:150px'   placeholder="请输入数字"
			            v-decorator="[
			              'subsistingCycle',baseform.subsistingCycle
			            ]"
			          />
			        </a-col>
			        <a-col :span="12">
			            <!-- <a-select defaultValue="0" style="width: 120px" >
					      <a-select-option value="0">月</a-select-option>
					      <a-select-option value="1">周</a-select-option>
					      <a-select-option value="2" >半年</a-select-option>
					      <a-select-option value="3">年</a-select-option>
					    </a-select> -->
			        </a-col>
			      </a-row>
		      </a-form-item>
		      <a-form-item
		        label="兑付方式"
		        :label-col="formItemLayout.labelCol"
		        :wrapper-col="formItemLayout.wrapperCol"
		      >
		          <a-row :gutter="8">
			        <a-col :span="12">
			           <a-select v-decorator="[ 'cash' ]" placeholder='请选择' >
					      <a-select-option value="1">年</a-select-option>
					      <a-select-option value="2">半年</a-select-option>
					      <a-select-option value="3" >季度</a-select-option>
					      <a-select-option value="4">自然季度</a-select-option>
					      <a-select-option value="5">自然半年付息</a-select-option>
					      <a-select-option value="6">一次性到期本息</a-select-option>
					    </a-select>
					</a-col>
				</a-row>
		      </a-form-item>
		      
		      <a-form-item
		        label="发行方"
		        :label-col="formItemLayout.labelCol"
		        :wrapper-col="formItemLayout.wrapperCol"
		      >
		           <a-input placeholder="请输入"  v-decorator="[ 'issuer',baseform.issuer ]"/>
		      </a-form-item>
		      <a-form-item
		        label="增信方"
		        :label-col="formItemLayout.labelCol"
		        :wrapper-col="formItemLayout.wrapperCol"
		      >
		           <a-input placeholder="请输入"  v-decorator="[ 'increasingCredit',baseform.increasingCredit ]"/>
		      </a-form-item>
		      <a-row  class='relative'>
			      <a-form-item
			        label="增信方式"
			        :label-col="formItemLayout.labelCol"
			        :wrapper-col="formItemLayout.wrapperCol"
			        
			      >
			           <a-radio-group   v-decorator="[ 'increasingCreditMode',baseform.increasingCreditMode]" >
					    <a-radio value="1">保证担保</a-radio>
					    <a-radio value="2">差额补足</a-radio>
					    <a-radio value="3">保证兑付</a-radio>
					    <a-radio value="4">应收确权</a-radio>
					    <a-radio value="5">其他 </a-radio>
					  </a-radio-group>
			      </a-form-item>
			      <a-form-item  v-show="form.getFieldValue('increasingCreditMode') ==5"  class='relative' style='margin-left: 28%;'  >
			      		<a-input  style="width: 200px; margin-left: 10px;}"  v-decorator="['increasingCreditModeValue',{rules:[{required:form.getFieldValue('increasingCreditMode') ==5 ? true:false,message:'请输入'}]}]"/>
			      </a-form-item>
			  </a-row>
		      <a-form-item
		        label="承销方"
		        :label-col="formItemLayout.labelCol"
		        :wrapper-col="formItemLayout.wrapperCol"
		      >
		           <a-input placeholder="请输入"  v-decorator="[ 'underwriter',baseform.underwriter ]" />
		      </a-form-item>
		      
		      <a-form-item
		        label="产品发行时间"
		        :label-col="formItemLayout.labelCol"
		        :wrapper-col="formItemLayout.wrapperCol"
		      >
		           <a-date-picker  v-decorator="['releaseTime',baseform.releaseTime ]"  />
		      </a-form-item> 
		      <a-form-item
		        label="产品结构图"
		        :label-col="formItemLayout.labelCol"
		        :wrapper-col="formItemLayout.wrapperCol"
		      >
		           <fileUpload   :fileList='prdConstruction'  v-on:uploading='($event)=>{prdConstruction = $event.fileList}'  v-on:removeFile='removeFile($event,1)'  uptip='仅支持上传一个文件，格式为图片格式'  :onefile='true' ></fileUpload>
		      </a-form-item>
		       <a-form-item
		        label="产品亮点"
		        :label-col="formItemLayout.labelCol"
		        :wrapper-col="formItemLayout.wrapperCol"
		      > 
		      	<a-textarea rows='5'  v-decorator="['highlight']"/>
		      </a-form-item>
		      <a-form-item
		        label="收益描述"
		        :label-col="formItemLayout.labelCol"
		        :wrapper-col="formItemLayout.wrapperCol"
		      > 
		      	<a-textarea rows='5' v-decorator="['benefitDescription']"/>
		      </a-form-item>
		      <a-form-item
		        label="产品标签"
		        :label-col="formItemLayout.labelCol"
		        :wrapper-col="formItemLayout.wrapperCol"
		      >  
		      	 <ul  class='productTag' style="margin-bottom: 0">
		      	 	<li  v-for='(item,index) in productTagdata' :key='index'  @click='checkedTag(item)'  ><button type="button"  :class='{active:item.checked==true}'>{{item.title}}</button></li>
		      	 </ul>
		      	 <a-button type="dashed"  @click='visible=true'  class='mr20'>添加</a-button> 
		      	 <a-input  v-decorator="['tag']"  style='display: none;' />
		      </a-form-item>
		       <a-form-item
		        label="产品发行进度"
		        :label-col="formItemLayout.labelCol"
		        :wrapper-col="formItemLayout.wrapperCol"
		      >
		           <a-textarea placeholder="请输入"  v-decorator="['issueProgress']"  rows='3'/>
		      </a-form-item>
		      <a-form-item
		        label="产品Q&A"
		        :label-col="formItemLayout.labelCol"
		        :wrapper-col="formItemLayout.wrapperCol"
		      >		 
		      		<ul  style="margin-bottom: 0"> 
		      			<li  v-for='(item,index) in currentQA'  :key='index'   class='relative'>Q：{{item.question}}  
		      			<span  style='color: red'>A：{{item.answer}}</span>  
		      			<a-popconfirm title="确认删除当前数据？" @confirm="delQAdata(index)"   okText="确认" cancelText="取消">
						    <a-icon type="delete" class='absolute  cursor'  style='right:0;top:13px;'  />
						</a-popconfirm>
		      			</li>
		      		</ul>
		           <a-button type="dashed"  @click='QAadd()' >添加</a-button> 
		      </a-form-item>
		      <a-form-item
		        label="是否为推荐产品"
		        :label-col="formItemLayout.labelCol"
		        :wrapper-col="formItemLayout.wrapperCol"
		      >
		            <a-radio-group name="radioGroup" v-decorator="['isRecommend',baseform.isRecommend]">
					    <a-radio value="1">是</a-radio>
					    <a-radio value="0">否</a-radio>
					</a-radio-group>
		      </a-form-item>
		      <a-form-item
		        label="可见用户组"
		        :label-col="formItemLayout.labelCol"
		        :wrapper-col="formItemLayout.wrapperCol"
		      >
		           <a-checkbox-group :options="plainOptions" v-decorator="[ 'roleList',baseform.roleList ]"     />
		      </a-form-item>

			<a-form-item
				label="相关资料"
				:label-col="formItemLayout.labelCol"
				:wrapper-col="formItemLayout.wrapperCol"
			> 
				 <fileUpload   :fileList='RelatedFileList'  v-on:uploading='($event)=>{RelatedFileList = $event.fileList}'  v-on:removeFile='removeFile($event,2)'></fileUpload>
				 
			</a-form-item>


			<a-form-item  v-if='isEdit'  style='display: none;'>
				 <a-input    v-decorator="[ 'code']"/>
			</a-form-item>
			<a-form-item
				:wrapper-col="buttonItemLayout.wrapperCol"
			>
				<a-button type="primary"  html-type="submit"  class='mr20'>
					提交
				</a-button>
				<a-button @click='cancel_to_back'> 取消 </a-button> 
			</a-form-item>
    	</a-form> 
		<a-modal :width='200'
	      title="添加新标签"
	      :visible="visible"
	      @ok="handleAddTag" 
	      @cancel="visible=false;newTagName=''"
	      cancelText='取消'
	      okText='确认'
	    >
	       名称：<a-input  style='width: 152px;'  v-model='newTagName'/>
	    </a-modal>
	    <QAProductModal  ref='QAmodalForm'  :visible='QAadd_visible' :writeData='currentQA' v-on:handleCancel='QAadd_visible=false'  v-on:handleOk='finishQAModal($event)'></QAProductModal>
   </a-spin>
 
</template>

<script>
import  fileUpload  from  '@/components/common/fileUpload'
import  QAProductModal  from  '@/components/product/QAProductModal'

import { RoleList }  from  '@/api/system/index'
import { detailProduct,submitProduct,list_QA }  from  '@/api/product/index'

import moment  from 'moment'
export default {
  name: 'productAdd',
  data () {
    return {
    	spinning:false,
    	indicator:<a-icon type="loading-3-quarters"  spin  style="{ fontSize: '16px' }"/> ,
    	delayTime:500,
    	plainOptions:[],/*角色列表 多选框*/
      	QAdata:[],/*QA列表 option*/
      	productTagdata:[  /*产品标签 option*/
			{title:'AA评级',checked:false},
			{title:'AA-评级',checked:false},
			{title:'AA+评级',checked:false},
			{title:'百强县',checked:false},
			{title:'发达地区',checked:false},
			{title:'地产30强',checked:false},
			{title:'地产10强',checked:false},
			{title:'地产50强',checked:false},
			{title:'公开市场发债主体',checked:false},
			{title:'市级平台',checked:false},
		], 
		visible:false,/*添加标签 modal-show*/
		newTagName:'',/*输入新标签 绑定model*/
		QAadd_visible:false,//产品QA modal-show
		currentQA:[],//已经填过的QA集，对比QA option
    	/*form  布局*/
      	formLayout:'horizontal', 
      	isEdit:false, 
      	/*form-rule 必填规则&需要初始值的input*/
	    baseform:{
	    	code:{initialValue:''},

      		name: {rules: [{ required: true, message: '请输入产品名称' },{ whitespace : true ,message:'当前输入不能为空'}]},
      		type:{rules: [{ required: true, message: '请选择产品类型' }],initialValue:''},
      		size:{initialValue:'',rules: [{ required: true, message: '请输入产品规模' }]},
      		financingSubjectNature:{initialValue:'',rules: [{ required: true, message: '请选择' }]},
      		 
			startingAmt:{initialValue:'',rules: [{ required: true, message: '请输入' }]}, 
      		subsistingCycle:{initialValue:'',rules: [{ required: true, message: '请输入存续周期' }]},
      		issuer:{initialValue:'',rules: [{ required: true, message: '请输入' }]}, 
      		releaseTime:{initialValue:null,rules: [{ required: true, message: '请选择日期' }]}, 

      		/*初始值为数组的 必须设置为[]*/
      		roleList:{initialValue:[]},
      		isRecommend:{initialValue:'0'},
      	},
 
	    RelatedFileList:[],//相关附件
	    prdConstruction:[],//结构图filelist/*只允许有一个文件，图片格式*/ 

    }
  },
  beforeCreate () {
    this.form = this.$form.createForm(this);
  },
  created(){
  		/*********初始化*********/
  		/*option */
  		this.pageInit()
  		/*产品分类值*/
  		this.baseform.type.initialValue = this.$route.hash.slice(1)
  		/*form-add*/
  		this.isEdit = false
  		/*if-form-edit*/
        let routeCode = this.$route.query.code 
        if(routeCode){
        	this.isEdit = true
        	this.getDetail(routeCode)
        }
  },
  methods:{
  	/*********初始化*********/
  	pageInit(){
  		/*用户组角色*/
  		RoleList({pageSize:100}).then((res)=>{
  			if(res.data.flag == true){
  				this.plainOptions = res.data.dataList.map((item)=>{
	  				return {
	  					label:item.name,
	  					value:item.code,
	  				}
	  			})
  			} 
  		})
  		list_QA({pageSize:100}).then((res)=>{
			if(res.data.flag == true){
				this.QAdata = res.data.dataList 
			} 
        })
  	},
  	//获取编辑详情
  	getDetail(code){
  		this.spinning = true
  		detailProduct(code).then((res)=>{
  			if(res.data.flag == true){
  				let data  =  res.data.data
  				this.form.setFieldsValue({
  						code,

  						name:data.name,
  						type:data.type, 
  						size:data.size,
  						financingSubjectNature:data.financingSubjectNature, 

  						startingAmt:data.startingAmt,
  						subsistingCycle:data.subsistingCycle,
  						cash:data.cash,
  						issuer:data.issuer,

  						increasingCredit:data.increasingCredit,
  						increasingCreditMode:data.increasingCreditMode,
  						increasingCreditModeValue:data.increasingCreditModeValue,
  						underwriter:data.underwriter,

  						releaseTime:data.releaseTime ? moment(data.releaseTime) : null,/*moment 设置为空时，需要设为null  "" & {} 均会warning*/ 
  						//结构图文件 ·····
  						highlight:this.saveSpace_to_str(data.highlight),
  						benefitDescription:this.saveSpace_to_str(data.benefitDescription), 
  						//产品标签 ·····
  						issueProgress:this.saveSpace_to_str(data.issueProgress),//产品发行进度
  						isRecommend:data.isRecommend,//是否推荐
  						//可见用户组·····
  						//相关资料 ·····
  				})

  				//结构图文件
  				this.prdConstruction = this.FormEditFile(data.imageList)
  				//产品标签
  				this.changeTag(data.tag)
  				//产品QA
  				this.currentQA =  data.faqList 
  				/*可见客户组回填 [{code:''}]=>['']  */ 
  				this.form.setFieldsValue({roleList:this.Recontent_fromcode(data.roleList)}) 
  				//相关文件
  				this.RelatedFileList = this.FormEditFile(data.fileVOList) 
  			}
  			this.spinning = false
  		})
  	}, 
  	
  	/*********页面功能函数*********/ 
  	/*提交表单*/
	handleSubmit (e) {
		let that = this,url
		e.preventDefault(); 
		this.form.validateFields((err, values) => {
			if (!err) {
			  //textarea格式保留
			  values.highlight = this.strSpace_to_save(values.highlight)
			  values.benefitDescription = this.strSpace_to_save(values.benefitDescription)
			  values.issueProgress = this.strSpace_to_save(values.issueProgress)
			  /*角色上传格式处理 [{code:''}] 必须设置initialValue=[]*/ 
			  values.roleList = this.RequireCodeToSub(values.roleList) 
			  /*上传文件格式处理 [{code:''}]*/ 
			  values.fileVOList = this.ReFileCodeToSub(this.RelatedFileList)
			  values.imageList = this.ReFileCodeToSub(this.prdConstruction)
			  /*产品标签 []=>''*/
			  values.tag =''/*初始为字符串*/
			  this.productTagdata.forEach((item)=>{
			  	values.tag += item.checked == true ? item.title+',' : ''
			  })   
			  //产品QA
			  values.faqList = this.currentQA

			  /*编辑或新增 上传路径配置*/
			  if(that.isEdit == true){
			  	url = '/op/product/modify_product'    //修改 项目 T
			  }
			  else{
			  	url='/op/product/create_product'      //新增 项目
			  }
			  // console.log('Received values of form: ', values);
			  submitProduct(url,values).then((res)=>{
			  	if(res.data.flag == true){
			  		that.$message.success(res.data.msg)
			  		that.$router.push('/product#'+values.type)
			  	}
			  })
			}
			else{
				console.log(err)
				this.$message.warning('表单还有必填项未填入') 
			}
		});
	},
	//返回
	cancel_to_back(){
		let num = this.form.getFieldValue('type')
		this.$router.push('/product#'+num)
	},
	//改变标签checked状态
	checkedTag(e){ 
		e.checked = !e.checked
	},

  	/*********组件函数*********/ 
  	// 新增QA-modal
  	QAadd(){
  		this.$refs.QAmodalForm.$emit('openDialog',this.QAdata)
      	this.QAadd_visible = true
  	},
  	//成功新增回调
  	finishQAModal(e){
  		// console.log(e) pushQ&A
  		this.currentQA.push({question:e.question,answer:e.answer})
  		this.$forceUpdate();//强制数组数据重新渲染 
  		this.QAadd_visible = false
  	},
  	delQAdata(index){
  		this.currentQA.splice(index,1) 
  	},

  	handleAddTag(){
		this.productTagdata.push({title:this.newTagName,checked:true}) 
		this.newTagName = ''
		this.visible = false
	}, 
    uploading(e){
      this.fileData = e.fileList
    },
    /*移除文件*/
    removeFile(e,num){
      // console.log(e)
      if(num==1){
      		this.removeFile_fromList(e,this.prdConstruction) 
      }
      if(num == 2){
      		this.removeFile_fromList(e,this.RelatedFileList) 
       } 
    },
	
	/*********通用工具函数*********/  
	changeTag(str){
		// console.log(str)//编辑后重置为无 ''
		if(str==''){
			return 
		}
		let arr = str.split(',')
		// 已经填写的元素与option比较，重新放入数组，并加上checked属性 
		arr.forEach((item,index)=>{ 
			this.productTagdata.forEach((it)=>{
				if(it.title == item){
					it.checked = true
					/*删除arr中已经跟option对比过的项，剩下自创项*/
					arr.splice(index,1,'')
				}
			})
		})
		/*自创项的重填*/
		arr.forEach((item)=>{
			item=='' ? '' : this.productTagdata.push({title:item,checked:true})
		})  
	},  
 
  },
	computed: {
		formItemLayout () {
			const { formLayout } = this;
			return formLayout === 'horizontal' ? {
			labelCol: {md:{span:5},lg:{ span: 7 }},  //label 标签布局
			wrapperCol: {xxl:{ span: 8 },xl:{ span : 11},lg:{ span :14 },md:{ span : 16 },xs:{ span :24}}, //需要为输入控件设置布局样式时，使用该属性，用法同 labelCol
			} : {};
		},
		buttonItemLayout () {
			const { formLayout } = this;
			return formLayout === 'horizontal' ? {
			wrapperCol: { span: 14, offset: 7 },
			} : {};
		},
		
	},
  components: {
    fileUpload,
    QAProductModal
  },
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
.productTag li{display: inline-block;margin-right: 10px;}
.productTag li>button{height: 32px;line-height: 32px;background-color: #fff;border:1px solid #ccc;border-radius: 19px;padding:0 15px;outline: none;}
.productTag li>button:hover{cursor: pointer;}
.productTag li>button.active{border-color:#1890ff;color:#1890ff;}
</style>
